package studyguide.ch09.input;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

public class InputCanvas extends Canvas {

	// Jump STEP_SIZE pixels at every button press
	private static final int STEP_SIZE = 5;
	
	// Ball position
	private int ballXPosition = 0;
	private int ballYPosition = 0;
	
	protected void paint(Graphics g) {
		// Clear screen before painting
		g.setColor(255, 255, 255); // White
		g.fillRect(0, 0, getWidth(), getHeight());
		
		// Ball diameter will be 1/10 of screen size
		int objectDimension = getWidth() / 10;
		
		// Draw the ball
		g.setColor(0, 0, 0); // Black
		g.fillArc(ballXPosition, ballYPosition, objectDimension, objectDimension, 0, 360);
	}

	protected void keyPressed(int keyCode) {
		System.out.println("Key Pressed:" + getKeyName(keyCode));
		moveBall(keyCode);
	}

	protected void keyRepeated(int keyCode) {
		System.out.println("Key Repeated:" + getKeyName(keyCode));
		moveBall(keyCode);
	}

	private void moveBall(int keyCode) {
		int gameKey = getGameAction(keyCode);
		if (gameKey == UP) {
			ballYPosition -= STEP_SIZE;
		} else if (gameKey == DOWN) {
			ballYPosition += STEP_SIZE;
		} else if (gameKey == LEFT) {
			ballXPosition -= STEP_SIZE;
		} else if (gameKey == RIGHT) {
			ballXPosition += STEP_SIZE;
		}
		
		// Ask for a screen repaint
		repaint();
	}

}
